package dome1.stackdome;

import java.util.Arrays;

public class MyStack<Integer> {
    public int[] elem;//整形数组
    public int usedSize;//1.记录当前数组的数据的有效个数。2.可以当做下标使用
    public static final int DEFAULT_CAPACITY = 10;//默认容量
    public MyStack(){
        this.elem = new int[DEFAULT_CAPACITY];
    }
    //压栈 入栈
    public void push(int val){
        if(isFull()){
            this.elem = Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize++] = val;
    }
    //检查栈是否需要扩容
    public boolean isFull(){
        return usedSize == elem.length;
    }
    //出栈
    public int pop(){
        if(isEmpty()){
            throw new EmptyStackException("栈为空");
        }
        int oldVal =  elem[usedSize-1];
        usedSize--;
        //elem[usedSize] = null;//引用类型时用null;
        return oldVal;
    }
    //检查栈里有没有数据
    public boolean isEmpty(){
        return usedSize == 0;
    }
    public int peek(){
        if(isEmpty()){
            throw new EmptyStackException("栈为空");
        }
        return elem[usedSize-1];
    }
}
